<?php
class templates{
	/*
	 * Cache of templates already loaded on this page
	 */
	public $cache = array();

	/*
	 * Get a template
	 */
	public function get($template){
		global $db, $phprpg, $theme;
		if(isset($this->cache[$template])){
			return $this->cache[$template];
		}else{
			$query = $db->select("templates","*","`name`='{$template}' AND `templateset` IN ({$theme['templateset']},1,-1)");
			if($db->recordcount($query) == 1){
				$t = $db->fetchrow($query);
				$t['template'] = str_replace("<html>","<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\"  xml:lang=\"en\">",$t['template']);
				$return = "<!-- Start of {$template} -->\n";
				//$return .= addslashes($t['template']);
				$return = str_replace("\\'", "'", addslashes($t['template']));
				$return .= "\n<!-- End of {$template} -->\n";
				$this->cache[$template] = $return;
				return $return;
			}else{
				$return = "<!-- Template {$template} doesn't exist -->\n";
				$this->cache[$template] = $return;
				return $return;
			}
		}
	}

	/*
	 * Add a new template
	 */
	public function add($name,$template,$sid="-1"){
		global $db, $phprpg;
		$insert['name'] = $name;
		$insert['template'] = $template;
		$insert['template_orig'] = $template;
		$insert['templateset'] = intval($sid);
		$db->insert("templates",$insert);
	}
	
	/*
	 * Edit an existing template
	 */
	public function edit($name,$template,$sid){
		global $db, $phprpg;
		$getTemplate = $db->select("templates","*","name='{$name}' AND sid=".intval($sid));
		if($db->recordcount($getTemplate) == 1){
			$update['name'] = $name;
			$update['template'] = $template;
			$db->update("templates",$update,"name='{$name}' AND templateset=".intval($sid));
		}
	}

	/*
	 * Revert a template to it's original
	 */
	public function revert($name,$sid){
		global $db, $phprpg;
	$getTemplate = $db->select("templates","*","name='{$name}' AND sid=".intval($sid));
		if($db->recordCount($getTemplate) == 1){
			$t = $db->fetchrow($getTemplate);
			$update['template'] = $t['template_orig'];
			$db->update("templates",$update,"name='{$name}' AND templateset=".intval($sid));
		}
	}
	
	/*
	 * Output Page
	 */
	public function output($page){
		global $db, $phprpg;
		echo stripslashes($page);
	}
}
?>